package com.homework.application.videoplayer;

import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.MediaController;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class VideoPlayer extends AppCompatActivity implements Button.OnClickListener {

    private VideoView videoView;
    private MediaPlayer mediaPlayer;
    //MediaController mediaController;   //自带进度控件
    private SeekBar seekBar, seekSound;
    private TextView textViewTime;
    private TextView textViewCurrentPosition;
    private TextView soundCurrentPosition;

    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        public void run() {
            if (videoView.isPlaying()) {
                int current = videoView.getCurrentPosition();
                seekBar.setProgress(current);
                textViewCurrentPosition.setText(time(videoView.getCurrentPosition()));
            }
            handler.postDelayed(runnable, 500);
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.play);
        videoView=findViewById(R.id.video);

        //开始、暂停、回放、停止按钮的定义
        ImageButton play = (ImageButton) findViewById(R.id.button_play);
        play.setOnClickListener(this);
        ImageButton pause = (ImageButton) findViewById(R.id.button_pause);
        pause.setOnClickListener(this);
        ImageButton turnback = (ImageButton) findViewById(R.id.button_turnback);
        turnback.setOnClickListener(this);
        ImageButton stop = (ImageButton) findViewById(R.id.button_stop);
        stop.setOnClickListener(this);

        //mediaController=new MediaController(this);
        //获取视频路径
        requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.INTERNET},0x123);

        textViewTime = (TextView) findViewById(R.id.textViewTime);

        //视频进度进度条
        seekBar = (SeekBar) findViewById(R.id.seekBar);
        //音量进度条
        seekSound = (SeekBar) findViewById(R.id.seekSound);

        // 为视频播放进度条添加进度更改事件
        seekBar.setOnSeekBarChangeListener(onSeekBarChangeListener);
        // 为音量进度条添加进度更改事件
        seekSound.setOnSeekBarChangeListener(onSeekSoundChangeListener);

        textViewCurrentPosition = (TextView) findViewById(R.id.textViewCurrentPosition);
        soundCurrentPosition = (TextView) findViewById(R.id.soundCurrentPosition);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if(requestCode==0x123&&grantResults[0]== PackageManager.PERMISSION_GRANTED){
            Log.d("MainActivity","Here is Ok");
            Log.d("MainActivity","Here is Ok");
            File videoFile=new File(getExternalFilesDir("").toString()+"/"+ Data.fileName);
            if(videoFile.exists()){
                //获取视频路径
                videoView.setVideoPath(videoFile.getPath());
                //mediaController.setMediaPlayer(videoView);
                //videoView.setMediaController(mediaController);
                videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                    @Override
                    public boolean onError(MediaPlayer mp, int what, int extra) {
                        return false;
                    }
                });
                videoView.requestFocus();
            }
        }
    }

    //开始、暂停、回放、停止按钮的实现
    @Override
    public void onClick(View v){
        switch (v.getId()){
            case R.id.button_play:
                play();
                break;
            case R.id.button_pause:
                videoView.pause();
                break;
            case R.id.button_turnback:
                videoView.seekTo(0);
                videoView.start();
                break;
            case R.id.button_stop:
                videoView.seekTo(Data.videoTime);
                break;
        }
    }


    protected void play() {

        if (!videoView.isPlaying()) {
            // 开始线程，更新进度条的刻度
            handler.postDelayed(runnable, 0);
            videoView.start();
            seekBar.setMax(videoView.getDuration());

        }

    }

    //视频播放进度条
    private SeekBar.OnSeekBarChangeListener onSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
        // 当进度条停止修改的时候触发
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // 取得当前进度条的刻度
            int progress = seekBar.getProgress();
            if (videoView.isPlaying()) {
                // 设置当前播放的位置
                videoView.seekTo(progress);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {

        }
    };


    //音量进度条
    private SeekBar.OnSeekBarChangeListener onSeekSoundChangeListener = new SeekBar.OnSeekBarChangeListener() {
        // 当进度条停止修改的时候触发
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // 取得当前进度条的刻度
            float progress = seekBar.getProgress()/100;
            try {
                Context context = videoView.getContext();
                AudioManager audioManager = (AudioManager) context.getSystemService(Service.AUDIO_SERVICE);
                int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);//(最大值是15)
                int flag = progress > 0 ? -1 : 1;
                currentVolume += flag * 0.1 * maxVolume;
                // 对currentVolume进行限制
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);

            } catch (Exception e) {
                e.printStackTrace();
            }
            int currrentProgress = seekBar.getProgress()/5;
            soundCurrentPosition.setText(currrentProgress+"/20");
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {

        }
    };

    //将获取的视频位置转换为时间内
    protected String time(long millionSeconds) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(millionSeconds);
        return simpleDateFormat.format(c.getTime());
    }


    /*
     *利用MediaPlayer
     *
    SurfaceView surfaceView;
    ImageButton play,pause,turnback,stop;
    MediaPlayer mPlayer;
    //视屏文件路径
    //File filePath=new File(getExternalFilesDir("").toString()+"/Echosmith - Over My Head_i0026vak82q_3_0 [mqms].mp4");
    //记录当前位置
    int position;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.play);
        //界面中的四个按钮
        play = (ImageButton) findViewById(R.id.button_play);
        pause = (ImageButton) findViewById(R.id.button_pause);
        turnback = (ImageButton) findViewById(R.id.button_turnback);
        stop = (ImageButton) findViewById(R.id.button_stop);
        //为四个按钮的单击事件绑定时间监听器
        play.setOnClickListener(this);
        pause.setOnClickListener(this);
        turnback.setOnClickListener(this);
        stop.setOnClickListener(this);
        //创建MediaPlayer
        mPlayer = new MediaPlayer();
        surfaceView = (SurfaceView) this.findViewById(R.id.video);
        //播放时打开屏幕
        surfaceView.getHolder().setKeepScreenOn(true);
        surfaceView.getHolder().addCallback(new SurfaceListener());
    }

    @Override
    public void onClick(View source){
        try{
            switch(source.getId()){
                //播放按钮被单击
                case R.id.button_play:
                    play();
                    break;
                //暂停按钮被单击
                case  R.id.button_pause:
                    if(mPlayer.isPlaying()){
                        mPlayer.pause();
                    }
                    else {
                        mPlayer.start();
                    }
                    break;
                //回放按钮被单击
                case R.id.button_turnback:
                    mPlayer.stop();
                    position=0;
                    mPlayer.start();
                //停止按钮被单击
                case R.id.button_stop:
                    if(mPlayer.isPlaying()) mPlayer.stop();
                    break;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void play() throws IOException{
        mPlayer.reset();
        //mPlayer.setAuxEffectSendLevel(AudioManager.STREAM_MUSIC);
        //设置需要播放的视屏
        mPlayer.setDataSource(filePath);
        //把视屏画面输出到SurfaceView
        mPlayer.setDisplay(surfaceView.getHolder());
        mPlayer.prepare();
        //获取窗口管理器
        WindowManager wManager = getWindowManager();
        DisplayMetrics metrics = new DisplayMetrics();
        //获取屏幕大小
        wManager.getDefaultDisplay().getMetrics(metrics);
        //设置视屏保持横比缩放到占满整个屏幕
        surfaceView.setLayoutParams(new WindowManager.LayoutParams(metrics.widthPixels
            ,mPlayer.getVideoHeight() * metrics.widthPixels/mPlayer.getVideoWidth()));
        mPlayer.start();
    }

    private class SurfaceListener implements SurfaceHolder.Callback{
        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height){
        }

        @Override
        public void surfaceCreated(SurfaceHolder holder){
            if(position > 0){
                try{
                    //开始播放
                    play();
                    //并从指定位置开始播放
                    mPlayer.seekTo(position);
                    position = 0;
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder){
        }
    }
    //当其他Activity被打开时，暂停播放
    @Override
    protected void onPause(){
        if (mPlayer.isPlaying()){
            //保存当前的播放位置
            position = mPlayer.getCurrentPosition();
            mPlayer.stop();
        }
        super.onPause();
    }
    @Override
    protected void onDestroy(){
        //停止播放
        if (mPlayer.isPlaying()) mPlayer.stop();
        //释放资源
        mPlayer.release();
        super.onDestroy();
    }*/
}
